<?php
namespace app\common\model;

use app\ux\UtilCurl;
use app\ux\UtilDb;
use think\Db;
use think\Env;
use think\Log;
use think\Model;

class RemoteModel extends Model
{

    protected $url;

    //继承父类initialize()

    protected function initialize()
    {
        parent::initialize();

        //对数据库执行的任何SQL操作进行监听
        self::logSql();
    }

    /**
     * 记录SQL脚本
     *
     * @return   [void]
     */
    public static function logSql($level = 'sql', $folder = 'sql')
    {

        //初始化调试监听文件日志路径
        //
        Log::init([
            'type'        => 'File',
            'path'        => APP_PATH . 'logs' . DS . $folder . DS,

            //ERROR 和SQL日志单独记录
            'apart_level' => ['error', 'sql'],
        ]);

        //对数据库执行的任何SQL操作进行监听
        //
        Db::listen(function ($sql, $time, $explain) {

            // 记录SQL
            Log::record($sql . ' [' . $time . 's]', 'sql');

            // 获取环境变量 如果不存在则使用默认值root
            $sql_explain = Env::get('sql_explain', false);

            if ($sql_explain) {
                
                // 查看性能分析结果
                Log::record($explain, 'sql');
            }
        });
    }

    /**
     * 清空表，复位自增主键列
     *
     * @return   void
     */
    public function clearTbl()
    {
        try {

            UtilDb::clearTable($this->table, 'id');

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 获取curl请求数据
     *
     * @return string  返回数据
     */
    public function updateToRecentById($url)
    {
        try {

            $curl = new UtilCurl;
            $rtn  = $curl->get($url);
            return ($rtn);

        } catch (\Exception $e) {

            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 请求插入目前为止所有数据
     *
     * @return int 插入数据量
     */
    public function getAllRecords()
    {
        try {

            //获取全部最新记录
            //
            $url        = $this->getUrl();
            $curlReturn = $this->updateToRecentById($url);
            $res        = json_decode($curlReturn, true);

            //批量插入
            //
            return ($this->chunkInsert($res['msg'], 1000));

        } catch (\Exception $e) {

            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 请求插入目前为止最新数据
     *
     * @return int 插入数据量
     */
    public function updateToRecent()
    {
        try {

            $field = 'id';
            $max   = $this->max($field);
            $max   = $max ? $max : -1;
            $url   = $this->getUrl($field, $max);

            $curlReturn = $this->updateToRecentById($url);
            $res        = json_decode($curlReturn, true);

            //日志记录用户数据请求结果
            //
            Log::init([
                'type' => 'File',
                'path' => APP_PATH . 'recharge' . DS . 'logs' . DS . 'update' . DS,
            ]);

            Log::record($curlReturn);

            if (empty($res['msg'])) {

                return 0;

            } else {

                if (is_array($res['msg'])) {

                    //获取最新记录插入数据库
                    //
                    return ($this->chunkInsert($res['msg'], 1000));
                }
            }
        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }

    /**
     * 根据下限id拼接请求url
     * 默认为id字段值为-1（所有记录）
     *
     * @return string 根据参数拼接请求url
     */
    public function getUrl($field = 'id', $value = -1)
    {

        $url = $this->url . "&{$field}={$value}";
        return $url;
    }

    /**
     * 批量插入数据
     *
     * @return int 插入数量
     */
    public function chunkInsert($arr, $num)
    {
        try {

            $count = 0;

            //批量分拆数组
            //
            $temp = array_chunk($arr, $num);

            foreach ($temp as $k => $v) {

                $res = $this->insertAll($v);
                $count += $res;
            }

            return $count;

        } catch (\Exception $e) {
            throw new \think\Exception('异常消息:' . $e->getMessage());
        }
    }
}
